import { store } from "@/store";
import { usePermissionStoreHook } from "@/store/modules/permission";

import AuthAPI, { type LoginFormData, type LoginResult, type selectAppFormData } from "@/api/auth";
import UserAPI, { type UserInfo } from "@/api/system/user";

import {
  setToken,
  clearToken,
  clearAppToken,
  setAppToken,
  clearHasOperatePermission,
} from "@/utils/auth";

export const useUserStore = defineStore("user", () => {
  const userInfo = useStorage<UserInfo>("userInfo", {} as UserInfo);
  const loginResult = useStorage<LoginResult>("loginResult", {} as LoginResult);

  /**
   * 登录
   *
   * @param {Object} LoginFormData - 登录表单数据
   * @returns {string}  返回类型login-直接登录 selectShop-选择店铺
   */
  function login(LoginFormData: LoginFormData) {
    return new Promise<string>((resolve, reject) => {
      // 记录登录时间
      sessionStorage.setItem("loginTime", new Date().getTime() + "");
      AuthAPI.login(LoginFormData)
        .then((data) => {
          const { token } = data;
          setToken("Bearer " + token); // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
          Object.assign(loginResult.value, { ...data });
          resolve("login");
        })
        .catch((error) => {
          reject(error);
        });
    });
  }
  /**
   * 选择app登录
   *
   * @param {Object} selectAppForm - 登录表单数据
   * @returns {string}
   */
  function selectApp(selectAppForm: selectAppFormData) {
    return new Promise<void>((resolve, reject) => {
      // 记录登录时间
      AuthAPI.selectApp(selectAppForm)
        .then((data) => {
          const { token } = data;
          setAppToken("Bearer " + token); // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
          Object.assign(loginResult.value, { ...data });
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  }
  /**
   * 通过手机登录
   *
   * @param {Object} LoginFormData - 登录表单数据
   * @returns {string}  返回类型login-直接登录 selectShop-选择店铺
   */
  function loginByMobile(LoginFormData: LoginFormData) {
    return new Promise<string>((resolve, reject) => {
      // 记录登录时间
      sessionStorage.setItem("loginTime", new Date().getTime() + "");
      AuthAPI.loginByMobile(LoginFormData)
        .then((data) => {
          const { token } = data;
          setToken("Bearer " + token); // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
          Object.assign(loginResult.value, { ...data });
          resolve("login");
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  /**
   * 获取用户信息
   *
   * @returns {UserInfo} 用户信息
   */
  function getUserInfo() {
    return new Promise<UserInfo>((resolve, reject) => {
      UserAPI.getInfo()
        .then((data) => {
          if (!data) {
            reject("Verification failed, please Login again.");
            return;
          }
          Object.assign(userInfo.value, { ...data });
          // 记录登录的商家id
          resolve(data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  /**
   * 登出
   */
  function logout() {
    return new Promise<void>((resolve, reject) => {
      AuthAPI.logout()
        .then(() => {
          clearUserData();
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  /**
   * 清理用户数据
   *
   * @returns
   */
  function clearUserData() {
    return new Promise<void>((resolve) => {
      clearToken();
      clearAppToken();
      clearHasOperatePermission();
      usePermissionStoreHook().resetRouter();
      resolve();
    });
  }

  return {
    userInfo,
    loginResult,
    getUserInfo,
    login,
    selectApp,
    loginByMobile,
    logout,
    clearUserData,
  };
});

/**
 * 用于在组件外部（如在Pinia Store 中）使用 Pinia 提供的 store 实例。
 * 官方文档解释了如何在组件外部使用 Pinia Store：
 * https://pinia.vuejs.org/core-concepts/outside-component-usage.html#using-a-store-outside-of-a-component
 */
export function useUserStoreHook() {
  return useUserStore(store);
}
